package org.community.test.controller;

import entity.CommonResult;
import lombok.Data;
import org.community.test.service.FileUtil;
import org.community.test.service.VideoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;


@RestController
@Data
public class VideoController {

    @Value("${server.port}")
    private int serverPort;

    @Resource
    private VideoService videoService;

    @Resource
    private FileUtil fileUtil;




    @PostMapping("/upload")
    public void uploadVideo(@RequestParam("file")MultipartFile multipartFile, HttpSession session) throws Exception {
        String name = multipartFile.getOriginalFilename();
        Map<String,String> fileNameMap = this.getFileUtil().fileNameRename(name);
        String fileNamePrefix = fileNameMap.get("prefix");
        String fileNameSuffix = fileNameMap.get("suffix");
        String newFileName = fileNamePrefix+"."+fileNameSuffix;
        uploadOriginal(newFileName,multipartFile);
        String videoName = this.getVideoService().uploadToM3u8(newFileName);
        session.setAttribute("video_id",videoName);

    }

    @PostMapping("/upload_original/{fileName}")
    public CommonResult<String> uploadOriginal(@PathVariable("fileName")String name, @RequestParam("file")MultipartFile  multipartFile) throws Exception {
        this.getVideoService().upload(name,multipartFile);
        return new CommonResult<>(200,"OK","upload successfully");

    }

    @RequestMapping("/download/{fileName}")
    public ResponseEntity<byte[]> download(@PathVariable("fileName")String name) {
        return this.getVideoService().download(name);
    }

    @RequestMapping("/preview/{fileName}")
    public ResponseEntity<byte[]>  preview(@PathVariable("fileName")String name) {
        return this.getVideoService().download(name);
    }

    @RequestMapping("/play/{fileName}")
    public ResponseEntity<byte[]>videoPlayCloud(@PathVariable("fileName")String name) {
        return this.getVideoService().videoPlayCloud(name);
    }




}
